package com.weng.cloud.starter.batch.factory;

import org.apache.ibatis.jdbc.SQL;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.sql.DataSource;

/**
 * @Author: weng
 * @Date: 2022/3/20
 * @Description: com.weng.cloud.starter.batch.factory
 */

public class CsvItemRdWrFactory {

    private DataSource dataSource;

    public CsvItemRdWrFactory(DataSource dataSource){
        this.dataSource = dataSource;
    }

    public <T> ItemReader<T> reader(Resource resource,String[] fields, Class<T> clz){
        // 使用FlatFileItemReader去读cvs文件，一行即一条数据
        FlatFileItemReader<T> reader = new FlatFileItemReader<>();
        // 设置文件处在路径
//        reader.setResource(new ClassPathResource("static/bloginfo.csv"));
        reader.setResource(resource);
        // entity与csv数据做映射
        reader.setLineMapper(new DefaultLineMapper<T>() {
            {
                setLineTokenizer(new DelimitedLineTokenizer() {
                    {
                        setNames(fields);
                    }
                });
                setFieldSetMapper(new BeanWrapperFieldSetMapper<T>() {
                    {
                        setTargetType(clz);
                    }
                });
            }
        });
        return reader;
    }

    public <T> ItemReader<T> reader(String path,String[] fields, Class<T> clz){
        return this.reader(new ClassPathResource(path),fields,clz);
    }

    public <T> ItemWriter<T> writer(SQL sql){
        // 使用jdbcBcatchItemWrite写数据到数据库中
        JdbcBatchItemWriter<T> writer = new JdbcBatchItemWriter<>();
        // 设置有参数的sql语句
        writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<T>());
        writer.setSql(sql.toString());
        writer.setDataSource(dataSource);
        return writer;
    }
}
